import json
import random
import time
import requests
from settings import *
import pymongo

class Auth:
    '''
    实现刷新token
    '''
    auth_accounts = []

    def __init__(self):
        self.interval = 60 * 60 * 23
        self.client = pymongo.MongoClient(MONGO_URL)
        self.db = self.client[MONGO_DATABASE]


    def refresh_token(self):
        '''
        刷新token，并保存到数据库
        :param app_id:
        :return:
        '''
        auth_info = self.db[COL_AUTH_INFO].find({})
        for auth_params in auth_info:
            refresh_auth_info = self.get_token(auth_params)
            item={}
            item['app_id'] = auth_params['app_id']
            item['secret'] = auth_params['secret']
            item['corp_name'] = auth_params['corp_name']
            item.update(refresh_auth_info)
            self.db[COL_AUTH_INFO].update_one({'app_id': item['app_id']}, {'$set': item},True)

    def get_token(self, auth_params):
        '''
        先获取token
        :param auth_params:
        :return: refresh_auth_info
        '''
        common_parameters = {
            'access_token': auth_params['access_token'],
            'timestamp': int(time.time()),
            'nonce': str(time.time()) + str(random.randint(0, 999999)),
        }

        params = {
            "client_id": auth_params['app_id'],
            "client_secret": auth_params['secret'],
            "grant_type": "refresh_token",
            "refresh_token": auth_params['refresh_token']
        }

        params.update(common_parameters)
        for k in params:
            if type(params[k]) is not str:
                params[k] = json.dumps(params[k])
        print('params:',params)
        resp = requests.get(GET_TOKEN, params=params)
        print(json.loads(resp.text))
        data = json.loads(resp.text)['data']
        print('data:', data)
        result = {
            'access_token': data.get('access_token'),
            'refresh_token': data.get('refresh_token'),
            'access_token_expires_in': data.get('access_token_expires_in'),
            'refresh_token_expires_in': data.get('refresh_token_expires_in',999999999),

        }
        return result

    def get_auth_accounts(self):
        '''
        获取授权的账户id，保存到数据库
        :return:
        '''
        auth_info = self.db[COL_AUTH_INFO].find({})
        for auth_params in auth_info:
            accounts = self.api_get_auth_accounts(auth_params)
            for account in accounts:
                item = {}
                item['account_id'] = account.get("account_id")
                item['status'] = 1
                item['app_id'] = auth_params['app_id']
                item['access_token'] = auth_params['access_token']
                item['refresh_token'] = auth_params['refresh_token']

                self.db[COL_AUTH_ACCOUNTS].update_one({'account_id': item.get('account_id')}, {'$set': item}, True)
            auth_accounts.clear()

    def api_get_auth_accounts(self,auth_params, page=1):
        '''
        从接口获取账户id
        :param auth_params:
        :param page:
        :return:
        '''

        common_parameters = {
            'access_token': auth_params['access_token'],
            'timestamp': int(time.time()),
            'nonce': str(time.time()) + str(random.randint(0, 999999)),
        }
        parameters = {
            "page": page,
            "page_size": 100,
        }
        parameters.update(common_parameters)
        for k in parameters:
            if type(parameters[k]) is not str:
                parameters[k] = json.dumps(parameters[k])
        resp = requests.get(ADVERTISER_INFO, params=parameters)
        result = json.loads(resp.text)['data']['list']
        page_size = len(result)
        if page_size >= 100:
            page += 1
            self.api_get_auth_accounts(auth_params, page)
        global auth_accounts
        auth_accounts += result
        return auth_accounts

    def run(self):
        while True:
            current_time = time.strftime('%Y-%m-%d %H:%M:%S')
            print(current_time.center(60,'*'))

            print('正在刷新token...')
            self.refresh_token()
            print('token更新完成.')

            print('正在更新授权账户...')
            self.get_auth_accounts()
            print('授权账户更新完成.')

        time.sleep(self.interval)


if __name__ == '__main__':
    auth = Auth()
    auth.run()







